/**
 * 
 */
package com.meiwenhui.sishuwujing.util;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.http.AjaxCallBack;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

import com.meiwenhui.sishuwujing.MainActivity;
import com.meiwenhui.sishuwujing.entities.Book;
import com.meiwenhui.sishuwujing.entities.Catalogue;

public class HttpUtil {

	public static final String GET_CATALOGUE_URL = "http://www.meiwenhui.com/api.php?action=getCategories";
	public static final String GET_BOOK_URL = "http://www.meiwenhui.com/api.php?action=getBooks&categoryId=%d";
	public static final String GET_CHAPTER_URL = "http://www.meiwenhui.com/api.php?action=getChapters&bookId=%d&offset=%d&limit=%d";

	public static final String GET_CHAPTER_COUNT_URL = "http://www.meiwenhui.com/api.php?action=getChapterCount&bookId=%d";

	public static final String GET_ARTICLE_URL = "";

	public static String get(String url) throws ClientProtocolException, IOException {
		Log.i("HttpUtil", url);
		FinalHttp http = new FinalHttp();
		HttpGet httpGet = new HttpGet(url);
		HttpClient httpClient = http.getHttpClient();
		HttpResponse response = httpClient.execute(httpGet, http.getHttpContext());
		String str = IOUtils.toString(response.getEntity().getContent());
		return str;
	}

	public static List<Catalogue> getCategories() throws ClientProtocolException, IOException, JSONException {
		List<Catalogue> catalogues = new ArrayList<Catalogue>(0);
		JSONArray jsonArray = new JSONArray(get(GET_CATALOGUE_URL));
		for (int i = 0; i < jsonArray.length(); i++) {
			JSONObject jsonObject = new JSONObject(jsonArray.get(i).toString());
			Catalogue category = new Catalogue();
			category.setCatalogueId(jsonObject.getInt("id"));
			category.setName(jsonObject.getString("name"));
			catalogues.add(category);
		}
		return catalogues;
	}

	public static List<Book> getBooks(int categoryId) throws ClientProtocolException, IOException, JSONException {
		List<Book> books = new ArrayList<Book>(0);
		JSONArray jsonArray = new JSONArray(get(String.format(GET_BOOK_URL, new Object[] { categoryId })));
		for (int j = 0; j < jsonArray.length(); j++) {
			JSONObject jsonObject = new JSONObject(jsonArray.get(j).toString());
			Book book = new Book();
			book.setBookId(jsonObject.getInt("id")); //
			book.setName(jsonObject.getString("name"));
			book.setCatalogueId(jsonObject.getInt("catalogueid"));
			books.add(book);
		}
		return books;
	}

	public static void ajax(String url, AjaxCallBack<Object> ajaxCallBack) {
		FinalHttp http = new FinalHttp();
		http.get(url, ajaxCallBack);
	}

}
